package com.codeoss.framework.impexp;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.converter.IConverter;
import com.codeoss.framework.converter.IConverterStore;
import com.codeoss.framework.data.metadata.Column;
import com.codeoss.framework.data.metadata.Query;
import com.codeoss.framework.data.metadata.Restrictions;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.metadata.TableData;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.util.StringUtils;
import com.codeoss.framework.view.datasource.DataSourceConfig;
import com.codeoss.framework.view.datasource.IDataSource;
import com.codeoss.framework.view.datasource.store.IDataSourceStore;

@Service
public class PropertiesImport implements IPropertiesImport {
	@Autowired
	private IDataSourceStore dataSourceStore;
	@Autowired
	private IConverterStore converterStore;
	@Autowired
	private ITableStore tableStore;
	@Override
	@Transactional
	public Map<String, Object> importProperties(YunContext yunContext,Table table, InputStream is) throws IOException {
		// TODO Auto-generated method stub
		Properties p = new Properties();
		p.load(is);
		boolean isNew=true;
		IDataSource dataSource = dataSourceStore.getDataSource(table.getAccessType());
		Map<String, Object> dataMap=null;
		Column codeColumn=table.getCodeColumn();
		Query query=new Query();
		query.add(Restrictions.eq(codeColumn.getColumnName(), p.get(codeColumn.getColumnName())));
		
		Object parentValue=getParentValue(yunContext, p, table);
		if(parentValue!=null) {
			query.add(Restrictions.eq(table.getParentColumn().getColumnName(),parentValue));
		}
		
		TableData tableData=dataSource.select(yunContext, table, query);
		if(tableData.getTotal()>0) {
			dataMap=tableData.getData().get(0);
			isNew=false;
		}else {
			dataMap = new HashMap<String, Object>();
		}
		List<Column> columnList = table.getAllColumnList();
		for (int i = 0; i < columnList.size(); i++) {
			Column column = columnList.get(i);
			if (column.isExportColumn()) {
				String sValue = p.getProperty(column.getColumnName());
				if(!StringUtils.isEmpty(sValue)) {
					if(column.getLookupInfo()!=null &&column.getLookupInfo().getDataSourceConfig()!=null) {
						DataSourceConfig dataSourceConfig=column.getLookupInfo().getDataSourceConfig();
						Table lookupTable=tableStore.get(dataSourceConfig.getTableName());
						IDataSource lookupDataSource=dataSourceStore.getDataSource(lookupTable.getAccessType());
						Query lookupQuery=new Query();
						lookupQuery.add(Restrictions.eq(lookupTable.getCodeColumn().getColumnName(), sValue));
						TableData lookupTableData=lookupDataSource.select(yunContext, lookupTable, lookupQuery);
						if(lookupTableData.getTotal()>0) {
							Map<String,Object> lookupDataMap=lookupTableData.getData().get(0);
							Object value =lookupDataMap.get(lookupTable.getPrimaryKeyColumn().getColumnName());
							dataMap.put(column.getColumnName(),value);
						}
					}else {
						IConverter converter = converterStore.getConverter(column.getDataType());
						Object value = converter.convertStringToObject(sValue);
						dataMap.put(column.getColumnName(), value);
					}
					
				}else {
					dataMap.put(column.getColumnName(),null);
				}
			}
		}
		if(table.isTreeTable()) {
			String parentCode=p.getProperty("_parent_code");
			if(!StringUtils.isEmpty(parentCode)) {
				Query parentQuery=new Query();
				parentQuery.add(Restrictions.eq(table.getCodeColumn().getColumnName(), parentCode));
				TableData parentTableData=dataSource.select(yunContext, table, parentQuery);
				if(parentTableData.getTotal()>0) {
					Map<String,Object> parentDataMap=parentTableData.getData().get(0);
					dataMap.put("parent_id", parentDataMap.get(table.getPrimaryKeyColumn().getColumnName()));	
				}
			}
		}
	    if(isNew) {
	    	dataSource.insert(yunContext, table, dataMap);
	    }else {
	    	dataSource.update(yunContext, table, dataMap);
	    }
	    return dataMap;
	}

	private Object getParentValue(YunContext yunContext,Properties p,Table table) {
		Column parentColumn=table.getParentColumn();
		if(parentColumn!=null) {
			String sParentValue=p.getProperty(parentColumn.getColumnName());
			if(!StringUtils.isEmpty(sParentValue)) {
				Table parentTable=tableStore.get(parentColumn.getLookupInfo().getDataSourceConfig().getTableName());
				IDataSource dataSource = dataSourceStore.getDataSource(parentTable.getAccessType());
				Query parentQuery=new Query();
				parentQuery.add(Restrictions.eq(parentTable.getCodeColumn().getColumnName(), sParentValue));
				TableData tableData=dataSource.select(yunContext, parentTable, parentQuery);
				if(tableData.getTotal()>0) {
					return tableData.getData().get(0).get(parentTable.getPrimaryKeyColumn().getColumnName());
				}
			}
		}
		return null;
	}
}
